package com.ficus.road.maintain.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ficus.road.maintain.core.model.DistrictVO;
import com.ficus.road.maintain.core.model.Hit;
import com.ficus.road.maintain.core.model.OperationLog;
import com.ficus.road.maintain.core.model.RoadSection;
import com.ficus.road.maintain.core.model.smart.District;
import com.ficus.road.maintain.dao.HitDao;
import com.ficus.road.maintain.dao.OperationLogDao;
import com.ficus.road.maintain.dao.RoadSectionDao;
import com.ficus.road.maintain.dao.smart.DistrictDao;
import com.ficus.road.maintain.service.DistrictService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;

/**
 * @author xiawen yang
 * @date 2021/8/16 下午6:29
 */
@RestController
@RequestMapping("/district")
public class DistrictController {

    @Autowired
    private DistrictService districtService;

    @Autowired
    private HitDao hitDao;

    @Autowired
    private OperationLogDao operationLogDao;

    @Autowired
    private RoadSectionDao roadSectionDao;

    @Autowired
    private DistrictDao districtDao;

    // 公路智能发现智能排序
    @RequestMapping(value = "/list",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('DISTRICT','ROAD_INDICATORS')")
    public ResponseEntity<List<District>> listDistrict() {
        List<District> districtList = districtDao.findAll();
        return new ResponseEntity<>(districtList, HttpStatus.OK);
    }

    @GetMapping("/{districtId}")
    @PreAuthorize("@rm.check('DISTRICT','ROAD_INDICATORS')")
    public ResponseEntity<List<DistrictVO>> getDistrictDetails(@PathVariable("districtId") String districtId) {
        List<DistrictVO> districtVOS = districtService.queryDistrict(districtId);
        return new ResponseEntity<>(districtVOS, HttpStatus.OK);
    }

    //第一步：从中海回调的记录中，将桩号重新写入hit表
    @PutMapping("/updateHitStakeNum")
    public ResponseEntity<Integer> updateHitStakeNum() {
        Query query = new Query(Criteria.where("title").is("中海回调"));
        List<OperationLog> operationLogList = operationLogDao.findByQuery(query);
        List<String> list = new ArrayList<>();
        Set<String> set = new HashSet<>();
        ObjectMapper mapper = new ObjectMapper();
        operationLogList.stream().forEach(operationLog -> {
            String params = operationLog.getParams();
            if (!StringUtils.isEmpty(params)) {
                Object[] objects = null;
                try {
                    objects = mapper.readValue(params, Object[].class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (ObjectUtils.isNotEmpty(objects)) {
                    String id = (String) objects[0];
                    HashMap map = (HashMap) objects[1];
                    String stakeNum = (String) map.get("stakeNum");
                    if (ObjectUtils.isNotEmpty(id) && ObjectUtils.isNotEmpty(stakeNum)) {
                        Hit fetch = hitDao.fetch(id);
                        if (ObjectUtils.isNotEmpty(fetch)) {
                            list.add(id);
                            set.add(id);
                            fetch.getAttrs().setStake(stakeNum);
                            hitDao.saveOrUpdate(fetch);
                        }
                    }
                }
            }
        });
        return new ResponseEntity<>(set.size(), HttpStatus.OK);
    }

    //第二步：根据病害桩号，更新病害所属的路段
    @PutMapping("/processHit")
    public ResponseEntity<Integer> updateRoadSections() {
        List<String> list = new ArrayList<>();
        Set<String> set = new HashSet<>();
        Query queryAll = new Query();
        List<Hit> hits = hitDao.findByQuery(queryAll);
        hits.forEach(hit -> {
            if (StringUtils.isNotBlank(hit.getAttrs().getRoadName())) {
                String[] roadName = hit.getAttrs().getRoadName().split(",");
                String stake = hit.getAttrs().getStake();
                if (StringUtils.isNotEmpty(stake)) {
                    Double stakeDouble = Double.parseDouble(stake);
                    Query query = new Query(Criteria.where("road_name").is(roadName[0])
                            .and("start_stake").lte(stakeDouble).and("end_stake").gte(stakeDouble));
                    RoadSection roadSection = roadSectionDao.findOne(query);
                    if (ObjectUtils.isNotEmpty(roadSection)) {
                        //更新病害的字段
                        hit.getAttrs().setRoadSection(roadSection.getId());
                        list.add(roadSection.getId());
                        set.add(roadSection.getId());
                        hitDao.saveOrUpdate(hit);
                    }
                }
            }
        });
        return new ResponseEntity<>(set.size(), HttpStatus.OK);
    }
}
